/**
 * @title 处理数据
 */
import axios from "axios";
import { pinyin } from "pinyin-pro";
import * as imageConversion from 'image-conversion';

export default {
  //这里对base64串进行操作，去掉url头，并转换为byte
  baseToType(src) {
    let bytes = window.atob(src.split(",")[1]);
    let arr = [];
    for (let i = 0; i < bytes.length; i++) {
      arr.push(bytes.charCodeAt(i));
    }
    return arr;
  },
  //文字转拼音
  TextToPinyin(text) {
    let logoTag = pinyin(text, {
      pattern: "first",
      toneType: "none",
    });
    logoTag = logoTag.replace(/\s*/g, "");
    return logoTag;
  },
  //转换成百分比
  changePercentage(num) {
    return Math.floor(num * 100) + "%";
  },
  //防抖 连续的操作中，只取指定的时间最后一次操作
  debounce(fn, t = 500) {
    let lastTime;
    return function () {
      clearTimeout(lastTime);
      const [that, args] = [this, arguments];
      lastTime = setTimeout(() => {
        fn.apply(that, args);
      }, t);
    };
  },
  throttle(fn, wait = 1000) {
    let pre = Date.now();
    return function () {
      let context = this;
      let args = arguments;
      let now = Date.now();
      if (now - pre >= wait) {
        fn.apply(context, args);
        pre = Date.now();
      }
    };
  },

  //截取rect
  fragmentreat(value) {
    if (!value.search("reat")) {
      return value.slice(4);
    } else {
      return value;
    }
  },
  //深拷贝
  deepcopy(value) {
    return JSON.parse(JSON.stringify(value));
  },
  //格式化时间
  formattime() {
    let y = new Date().getFullYear();
    let m = new Date().getMonth() + 1;
    m = m < 10 ? "0" + m : m;
    let d = new Date().getDate();
    d = d < 10 ? "0" + d : d;
    return y + "-" + m + "-" + d;
  },
  // 下载图片
  downloadURI(url, name) {
    let link = document.createElement("a");
    link.download = name;
    link.href = url;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    link = "";
  },
  //获取文本行数
  lineNumData(str) {
    str = str.replace(/(\r\n)|(\n)/g, "<br>");

    let string = str.split("<br>");
    if (string[string.length - 1] == "") {
      string.pop();
    }
    return string.length;
  },
  //获取数列文本数
  verticalNumData(str) {
    str = str.replace(/(\r\n)|(\n)/g, "<br>");
    let arr = str.split("<br>");
    if (arr[arr.length - 1] == "") {
      arr.pop();
    }
    /* 数组反转 */
    arr = arr.reverse();
    /* 找出最大长度 */
    let lengths = arr.map(function (a) {
      return a.length;
    });

    let maxIndex = lengths.indexOf(Math.max.apply(Math, lengths));
    let maxNum = lengths[maxIndex];
    return maxNum;
  },
  //换行裁切
  lineFeedCutData(str) {
    str = str.replace(/(\r\n)|(\n)/g, "<br>");
    let arr = str.split("<br>");
    if (arr[arr.length - 1] == "") {
      arr.pop();
    }
    /* 数组反转 */
    arr = arr.reverse();
    /* 找出最大长度 */
    let lengths = arr.map(function (a) {
      return a.length;
    });
    let maxIndex = lengths.indexOf(Math.max.apply(Math, lengths));
    let maxNum = lengths[maxIndex];
    let text = "";
    let item;
    /* 循环数组 */
    for (let i = 0; i <= maxNum - 1; i) {
      for (let j = 0; j <= arr.length - 1; j++) {
        if (i >= maxNum) {
          continue;
        }
        for (let s = 0; s <= arr.length - 1; s++) {
          item = arr[s][i];
          if (typeof item == "undefined") {
            text += "\u3000";
          } else {
            text += item;
          }
        }
        i++;
        /* 结尾换行 */
        text += "\n";
      }
    }
    return text;
  },
  //内容换成半角
   ToCDB(str) {
    var tmp = "";
    for (var i = 0; i < str.length; i++) {
      if (str.charCodeAt(i) > 65248 && str.charCodeAt(i) < 65375) {
        tmp += String.fromCharCode(str.charCodeAt(i) - 65248);
      }
      else {
        tmp += String.fromCharCode(str.charCodeAt(i));
      }
    }
    return tmp
  },
  //内容换成全角
  TtoDBC(str) {
    let result = "";
    for (let i = 0; i < str.length; i++) {
      let code = str.charCodeAt(i);
      if (code >= 33 && code <= 126) {
        result += String.fromCharCode(str.charCodeAt(i) + 65248);
      } else if (code == 32) {
        result += String.fromCharCode(str.charCodeAt(i) + 12288 - 32);
      } else {
        result += str.charAt(i);
      }
    }
    return result;
  },
  /***
    实现设置样式方法 css(dom, width, 200px) 或 css(dom, {width: '200px', color: 'red'})
    @dom    元素
    @key   样式名
    @value     样式值
    ***/
  css(dom, key, value) {
    if (typeof key === "string") {
      dom.style[key] = value;
    } else {
      for (let name in key) {
        this.css(dom, name, key[name]);
      }
    }
  },
  //转64位
  getBase64(url) {
    return new Promise((resolve) => {
      let Img = new Image();
      let dataURL = "";
      Img.setAttribute("crossOrigin", "Anonymous");
      Img.src = url + "?v=" + Math.random();
      Img.onload = function () {
        // 要先确保图片完整获取到，这是个异步事件
        let canvas = document.createElement("canvas"); // 创建canvas元素
        let width = Img.width; // 确保canvas的尺寸和图片一样
        let height = Img.height;
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").drawImage(Img, 0, 0, width, height); // 将图片绘制到canvas中
        dataURL = canvas.toDataURL("image/jpeg"); // 转换图片为dataURL
        resolve(dataURL);
      };
    });
  },
  //将base64转换为blob
  dataURLtoBlob(dataurl) {
    let arr = dataurl.split(","),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  },
  //将blob转换为file
  blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
  },
  // base64格式转换png
  base64ToBlob(urlData, type) {
    let arr = urlData.split(",");
    let array = arr[0].match(/:(.*?);/);
    let mime = (array && array.length > 1 ? array[1] : type) || type;
    // 去掉url的头，并转化为byte
    let bytes = window.atob(arr[1]);
    // 处理异常,将ascii码小于0的转换为大于0
    let ab = new ArrayBuffer(bytes.length);
    // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
    let ia = new Uint8Array(ab);
    for (let i = 0; i < bytes.length; i++) {
      ia[i] = bytes.charCodeAt(i);
    }
    return new Blob([ab], {
      type: mime,
    });
  },
  //logo图片跨域
  getBase64ByUrl(src, callback, outputFormat) {
    let xhr = new XMLHttpRequest();
    // eslint-disable-next-line no-debugger
    debugger;
    xhr.open("GET", src, true);
    xhr.responseType = "arraybuffer";
    xhr.onload = function () {
      if (xhr.status == 200) {
        let uInt8Array = new Uint8Array(xhr.response);
        let i = uInt8Array.length;
        let binaryString = new Array(i);
        while (i--) {
          binaryString[i] = String.fromCharCode(uInt8Array[i]);
        }
        let data = binaryString.join("");
        let base64 = window.btoa(data);
        let dataUrl =
          "data:" + (outputFormat || "image/png") + ";base64," + base64;
        callback.call(this, dataUrl);
      }
    };
    xhr.send();
  },
  getBase64r(url) {
    //const urlReplace = url.replace('http', 'https');
    let that = this;
    axios
      .get(url, {
        responseType: "blob",
        headers: { "Access-Control-Allow-Origin": "*" },
      })
      .then(function (response) {
        that.callBack(response);
      });
  },
  callBack(res) {
    let blob = new Blob([res]);
    let url = window.URL.createObjectURL(blob);
    this.setState({
      src: url,
    });
    // 释放url对象
    // window.URL.revokeObjectURL(url);
  },
  insertImg(url) {
    let _this = this;
    let image = new Image();
    image.src = url + "?v=" + Math.random();
    image.crossOrigin = "*";
    image.onload = function () {
      _this.getBase64Image(image);
    };
  },
  // 跨域图片转base64
  getBase64Image(img) {
    let canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    let ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    let dataURL = canvas.toDataURL("image/png");
    return dataURL;
  },
  //判断是http还是base64，如果是http就转base64
  srcTurnTheHTTPBase64(src) {
    if (src.indexOf("data:image") > -1) {
      // base64 图片操作
      return src;
    } else if (src.indexOf("http") > -1) {
      //path 图片操作
      src = this.imageUrlToBase64(src);
    }
  },
  imageUrlToBase64(img) {
    //一定要设置为let，不然图片不显示
    let image = new Image();
    let dataURL = "";
    //解决跨域问题
    image.setAttribute("crossOrigin", "anonymous");
    let imageUrl = img;
    image.src = imageUrl;
    //image.onload为异步加载
    image.onload = () => {
      let canvas = document.createElement("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      let context = canvas.getContext("2d");
      context.drawImage(image, 0, 0, image.width, image.height);
      let quality = 0.8;
      //这里的dataurl就是base64类型
      dataURL = canvas.toDataURL("image/jpeg", quality);
      //使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
      return dataURL; //dataURL就是转好的base64编码
    };
  },
  //图片大小超过2M,长/宽超过1280就压缩
  compressedImage(file) {
    let _URL = window.URL || window.webkitURL;
    let isLt2M = file.size / 1024; // 判定图片大小是否小于1.6MB
    // 这里需要计算出图片的长宽
     return new Promise((resolve) => {
      let img = new Image();
      img.onload = function () {
        file.width = img.width; // 获取到width放在了file属性上
        file.height = img.height; // 获取到height放在了file属性上
        let scale = 1;
        if (img.width > 812.4 || img.height > 812.4) {
          if (img.width >= img.height) {
            scale = 812.4 / img.width;
          } else if (img.width < img.height) {
            scale = 812.4 / img.height;
          }
        }
        if (isLt2M > 812.4) isLt2M = 812.4;
        imageConversion.compressAccurately(file, {
          size: isLt2M,
          width: img.width * scale,
          height: img.height * scale,
          // accuracy: 0.9,
          type: "image/png",
        }).then(res => {
          resolve(res)
        })
      };
      img.src = _URL.createObjectURL(file);
    });
  },
  compressedBack(file) {
    let _URL = window.URL || window.webkitURL;
    let isLt2M = file.size / 1024; // 判定图片大小是否小于1.6MB
    // 这里需要计算出图片的长宽
     return new Promise((resolve) => {
      let img = new Image();
      img.onload = function () {
        file.width = img.width; // 获取到width放在了file属性上
        file.height = img.height; // 获取到height放在了file属性上
        if (isLt2M > 1024) isLt2M = 1024;
        imageConversion.compressAccurately(file, {
          size: isLt2M,
          width: img.width,
          height: img.height,
          // accuracy: 0.9,
          type: "image/png",
        }).then(res => {
          resolve(res)
        })
      };
      img.src = _URL.createObjectURL(file); 
    });
  },
};
